import threading

# 问题：多线程 对 同一数据 做不同操作，可能导致 数据混乱
i = 0
lock = threading.Lock()


def run1():
    global i
    # 写法一
    if lock.acquire():
        for x in range(1000000):
            i += x
            i -= x
        lock.release()
    print(i)


def run2():
    global i
    # 写法二
    with lock:
        for x in range(1000000):
            i += x
            i -= x
    print(i)


if __name__ == '__main__':
    # lock = threading.Lock()
    thread1 = threading.Thread(target=run1)
    thread2 = threading.Thread(target=run2)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print('over')
